--
-- Author: shunguo.chen
-- Date: 2016-08-26 11:52:07
--
-- IMVoiceBtn

local ClassRef = app.mvc.createRenderClass(...)

function ClassRef.create(node, data)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.IMVoiceBtn))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init(data)
	return sprite
end

-- data = IMMessage/{audioPath=, audioDuration=}
function ClassRef:init(data)
	self.super.init(self, data)

	self:setContentSize(self._ui.blue:getContentSize())
	self._ui.blue:setTouchEnabled(false)
	self._ui.Button_voice:setTouchEnabled(false)
	
	self._ui.Button_voice:addClickEventListener(function()
			executeFunc(self._onBtnClick)
		end)

	self._isInPlay = false

	self:refresh()
end

function ClassRef:refresh()
	if not self._data then 
		self:setVisible(false)
		return
	end

	self:setVisible(true)
	if iskindof(self._data, "IMMessage") then
		local text
		local able = false
		if self._data.downloadState == im.MessageAttachState.Downloaded then
			-- text = string.format("%.1fs", self._data.audioDuration)
			able = true
		elseif self._data.downloadState == im.MessageAttachState.NeedDownload then
			-- text = L("点击下载")
			able = true
		elseif self._data.downloadState == im.MessageAttachState.Failed then
			text = L("tips_1150007")
		elseif self._data.downloadState == im.MessageAttachState.Downloading then
			
		end
		self:setBtnAble(able)
		if not text then
			if self._data.audioDuration > 0 then
				text = string.format("%.1fs", self._data.audioDuration)
			else
				text = L("tips_3000127")
			end
		end
		self:setTime(text)
	else
		self:setBtnAble(true)
		if self._data.audioDuration > 0 then
			self:setTime(string.format("%.1fs", self._data.audioDuration))
		else
			self:setTime(L("tips_3000127"))
		end
	end
end

function ClassRef:getHeight()
	return self:getContentSize().height
end

function ClassRef:setBtnAble(b)
	self._ui.Button_voice:setTouchEnabled(b)
end

function ClassRef:setTime(text)
	self._ui.Text_time:setString(text)
end

function ClassRef:setIsInPlay(b)
	self._isInPlay = b
end
function ClassRef:isInPlay()
	return self._isInPlay
end

function ClassRef:play()
	display.playTimeline(self, 0, true)
end

function ClassRef:stopPlay()
	display.pauseTimeline(self, "max")
end

function ClassRef:onBtnClick(cb)
	self._onBtnClick = cb
end

return ClassRef